<template>

  <div id="roleList">
    <el-container>
      <el-main>
        <el-row>
          <!-- 左边角色列表 start -->
          <el-col :span="leftLayoutWidth">
            <div class="grid-content gridLeft">
              <h4>角色树</h4>
              <el-row>
                <div class="userHandle">
                  <el-button type="primary" icon="el-icon-circle-plus-outline" round @click.native="openAddRole"
                             size="mini">
                    新增
                  </el-button>
                  <el-button type="success" icon="el-icon-edit" round @click.native="openUpdateRole" size="mini">修改
                  </el-button>
                  <el-button type="danger" icon="el-icon-delete" round @click.native="deleteRole" size="mini">删除
                  </el-button>
                </div>
              </el-row>
              <el-tree :data="roleTreeList" :props="roleProps" @node-click="roleTreeClick" highlight-current></el-tree>
            </div>
          </el-col>


          <!-- 右边权限列表、角色列表 start -->
          <el-col :span="rightLayoutWidth">
            <div class="grid-content  gridRight">
              <h4>角色权限</h4>
              <el-row>
                <div class="userHandle" style="text-align: left">
                  <el-button type="primary" icon="el-icon-circle-plus-outline" round
                             @click.native="openSaveRightRoleDialog"
                             size="mini">分配权限
                  </el-button>
                </div>
              </el-row>

              <!-- 父权限列表 -->
              <el-table
                :data="rightDataList"
                style="width: 100%"
              >

                <!-- 列表的首列拓展 -->
                <el-table-column type="expand">

                  <!-- 子权限列表模板 -->
                  <template slot-scope="props">
                    <!-- 子权限列表 start -->
                    <el-table
                      :data="props.row.childrenList"
                      style="width: 100%" :show-header="false" border>
                      <el-table-column
                        label="权限名称"
                        prop="sysRightName"
                        align="center">
                      </el-table-column>
                      <el-table-column
                        label="权限标识"
                        prop="sysRightPermission"
                        align="center">
                      </el-table-column>
                      <el-table-column
                        label="权限类型"
                        prop="sysRightType"
                        :formatter="formatSystemRightType"
                        align="center">
                      </el-table-column>
                      <el-table-column
                        label="权限状态"
                        prop="isEnabled"
                        :formatter="formatSystemRightIsEnabled"
                        align="center">
                      </el-table-column>
                    </el-table>
                    <!-- 子权限列表 end -->
                  </template>

                </el-table-column>

                <el-table-column
                  label="权限名称"
                  prop="sysRightName"
                  align="center">
                </el-table-column>
                <el-table-column
                  label="权限标识"
                  prop="sysRightPermission"
                  align="center">
                </el-table-column>
                <el-table-column
                  label="权限类型"
                  prop="sysRightType"
                  :formatter="formatSystemRightType"
                  align="center">
                </el-table-column>
                <el-table-column
                  label="权限状态"
                  prop="isEnabled"
                  :formatter="formatSystemRightIsEnabled"
                  align="center">
                </el-table-column>
              </el-table>

            </div>

            <!-- 右边用户列表 start -->
            <div class="grid-content gridRight">
              <h4>角色用户</h4>
              <el-row>
                <div class="userHandle" style="text-align: left">
                  <el-button type="primary" icon="el-icon-circle-plus-outline" round
                             @click.native="addUser"
                             size="mini">新增关联
                  </el-button>
                </div>
              </el-row>

              <!-- 用户列表数据 -->
              <el-table
                :data="userDataList"
                style="width: 100%">
                <el-table-column
                  prop="sysUserAccount"
                  label="用户账号"
                  align="center">
                </el-table-column>
                <el-table-column
                  prop="sysUserName"
                  label="用户名称"
                  align="center">
                </el-table-column>
                <el-table-column
                  prop="sysDept"
                  label="所属部门"
                  align="center"
                  :formatter="formatSysDeptName">
                </el-table-column>
                <el-table-column
                  prop="isLockedStr"
                  label="是否可用"
                  align="center"
                  :formatter="formatIsLocked">
                </el-table-column>
              </el-table>
              <el-pagination
                layout="prev, pager, next"
                :page-sizes="[5]"
                :page-size="userListPageSize"
                :total="userListPageTotal"
                @current-change="currentChangeUserListPage">
              </el-pagination>

            </div>
          </el-col>




        </el-row>

        <!-- 角色表单窗口 -->
        <el-dialog title="角色信息" :visible.sync="roleInfoDialog">
          <el-form :model="roleForm" ref="roleForm" label-position="left">
            <el-form-item label="角色名称" :label-width="formLabelWidth" prop="sysRoleName"
                          :rules="{required: true, message: '角色名称不能为空', trigger: 'blur'}">
              <el-input v-model="roleForm.sysRoleName" autocomplete="off" placeholder="角色名称"></el-input>
            </el-form-item>
            <el-form-item label="角色备注" :label-width="formLabelWidth">
              <el-input v-model="roleForm.sysRoleRemark" autocomplete="off" placeholder="角色备注"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button @click="roleInfoDialog = false">取 消</el-button>
            <el-button type="primary" @click="saveOrUpdateRole('roleForm')">确 定</el-button>
          </div>
        </el-dialog>

        <!-- 分配权限菜单窗口 -->
        <el-dialog title="分配权限菜单" :visible.sync="rightInfoDialog">
          <el-tree :data="rightTreeList" :props="rightProps"
                   show-checkbox
                   node-key="sysRightId"
                   ref="rightTree"
          ></el-tree>
          <div slot="footer" class="dialog-footer">
            <el-button @click="rightInfoDialog = false">取 消</el-button>
            <el-button type="primary" @click="savePrivilegeRole()">确 定</el-button>
          </div>
        </el-dialog>

        <!--新增用户列表菜单窗口-->
        <el-dialog title="用户" :visible.sync="addUserInfo">
          <el-table
            :data="UserList"
            highlight-current-row
            @row-click="handleCurrentChange"
            style="width: 100%">
            <el-table-column
              prop="sysUserAccount"
              label="用户账号"
              align="center">
            </el-table-column>
            <el-table-column
              prop="sysUserName"
              label="用户名称"
              align="center">
            </el-table-column>
            <el-table-column
              prop="sysDept"
              label="所属部门"
              align="center"
              :formatter="formatSysDeptName">
            </el-table-column>
            <el-table-column
              prop="isLockedStr"
              label="是否可用"
              align="center"
              :formatter="formatIsLocked">
            </el-table-column>
          </el-table>
          <el-pagination
            layout="prev, pager, next"
            :page-sizes="[5]"
            :page-size="userListPageSize"
            :total="userListPageTotal"
            @current-change="currentChangeUserListPage">
          </el-pagination>
          <div slot="footer" class="dialog-footer">
            <el-button @click="addUserInfo = false">取 消</el-button>
            <el-button type="primary" @click="saveUser()">确 定</el-button>
          </div>

        </el-dialog>
      </el-main>
    </el-container>
  </div>

</template>

<script>

  import api from "@/assets/js/system/role_list.js";
  import common from "@/assets/js/common/common.js";

  export default {
    data() {
      return {
        leftLayoutWidth: 6,//左边布局宽度格数
        rightLayoutWidth: 18,//右边布局宽度格数
        roleTreeList: [], //角色数据列表
        //树形角色定义的格式对应关系
        roleProps: {
          children: 'children',
          label: 'sysRoleName'
        },
        formLabelWidth: '120px', //form表单的宽度
        roleInfoDialog: false, //角色表单窗口
        //角色表单
        roleForm: {
          sysRoleId: null,
          sysRoleName: "",
          sysRoleRemark: ""
        },
        rightInfoDialog: false, //权限窗口开关
        rightTreeList: [], //分配权限的树形列表数据
        //树形权限定义的格式对应关系
        rightProps: {
          children: 'childrenList',
          label: 'sysRightName'
        },
        selectRightTreeList: [], //选中权限树的数据列表
        rightDataList: [], //右边权限列表
        //权限类型列表
        rightTypeList: [
          {
            value: "1",
            msg: "菜单"
          },
          {
            value: "2",
            msg: "按钮"
          }
        ],
        userDataList: [],  //右边用户列表
        userListPageTotal: 0,//用户列表总数
        userListPageSize: 10, //用户每页显示的数据量
        userListPageNo: 1,   //用户分页的当前页、
        addUserInfo: false,
        currentRow: null,
        UserList: []
      }
    },
    mounted: function () {
      //需要执行的方法可以在mounted中进行触发，其获取的数据可以赋到data中后，可以放在前面进行渲染
      this.getRoleList({});//获取角色分页列表
      this.getPrivilegeTree(); //加载权限树形数据
    },
    methods: {
      /**
       * 获取角色列表
       * */
      getRoleList(param) {
        api.getRoleList(param).then((res) => {
          if (res.data == null) {
            this.roleTreeList = null;
            return;
          }
          this.roleTreeList = res.data;
          this.$nextTick(() => {
            // treeBox 元素的ref   value 绑定的node-key
            //el-tree默认选中第一个
            this.$refs.treeBox.setCurrentKey(this.roleTreeList[0].sysRoleId);

            this.roleForm.sysRoleId = this.roleTreeList[0].sysRoleId;
            this.roleForm.sysRoleName = this.roleTreeList[0].sysRoleName;
            this.roleForm.sysRoleRemark = this.roleTreeList[0].sysRoleRemark;
            //根据角色加载权限列表
            this.getTreeListByRoleId();
            //根据角色加载用户列表
            this.getUserListByRoleId({
              sysRoleId: this.roleForm.sysRoleId,
              pageNo: 1,
              pageSize: this.userListPageSize
            });
          });
        });
      },
      /**
       * 角色树点击事件
       * */
      roleTreeClick(data) {
        //角色表单设置参数
        this.roleForm.sysRoleId = data.sysRoleId;
        this.roleForm.sysRoleName = data.sysRoleName;
        this.roleForm.sysRoleRemark = data.sysRoleRemark;
        //根据角色加载权限列表
        this.getTreeListByRoleId();
        //根据角色加载用户列表
        this.getUserListByRoleId({
          sysRoleId: this.roleForm.sysRoleId,
          pageNo: 1,
          pageSize: this.userListPageSize
        });
      },
      /**
       * 打开新增角色窗口
       * */
      openAddRole() {
        this.roleForm = {};//重置表单
        this.roleInfoDialog = true;
      },
      /**
       * 打开更新角色窗口
       * */
      openUpdateRole() {
        if (this.roleForm.sysRoleId == null) {
          common.message("请选择你需要修改的角色！", "warning");
          return;
        }
        this.roleInfoDialog = true;
      },
      /**
       * 保存角色
       * */
      saveOrUpdateRole(formName) {
        if (this.roleForm.sysRoleId == null) {
          this.addRole(formName);
        } else {
          this.updateRole(formName);
        }
      },
      /**
       * 新增角色
       * */
      addRole(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            api.addRole(this.roleForm).then((res) => {
              common.generalMessage(res); //提示框信息
              this.getRoleList();//重置角色列表
              this.roleInfoDialog = false; //关闭弹窗
            });
          } else {
            return false;
          }
        });
      },
      /**
       * 修改角色
       * */
      updateRole(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            api.updateRole(this.roleForm).then((res) => {
              common.generalMessage(res); //提示框信息
              this.getRoleList();//重置角色列表
              this.roleInfoDialog = false; //关闭弹窗
            });
          } else {
            return false;
          }
        });
      },
      /**
       * 删除角色
       * */
      deleteRole() {
        if (this.roleForm.sysRoleId == null) {
          common.message("请选择你需要删除的角色！", "warning");
          return;
        }
        this.$confirm("确认是否删除角色【" + this.roleForm.sysRoleName + "】", "是否继续?", '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          api.deleteRole({
            id: this.roleForm.sysRoleId
          }).then((res) => {
            common.generalMessage(res); //提示框信息
            if (res.code == 200) {
              this.getRoleList({});//重新加载树形数据
            }
          });
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
      },
      /**
       * 根据角色id获取权限列表
       * */
      getTreeListByRoleId() {
        if (this.roleForm.sysRoleId == null) {
          return;
        }
        api.getTreeListByRoleId({
          roleId: this.roleForm.sysRoleId
        }).then((res) => {
          this.rightDataList = res.data;
        });
      },
      /**
       * 根据列表的数据转换权限类型
       * */
      formatSystemRightType(row) {
        var msg = "";
        switch (row.sysRightType) {
          case "1":
            msg = "菜单";
            break;
          case "2":
            msg = "按钮";
            break;
          default:
            break;
        }
        return msg;
      },
      /**
       * 根据列表的数据转换权限状态
       * */
      formatSystemRightIsEnabled(row) {
        var msg = "";
        switch (row.isEnabled) {
          case "1":
            msg = "可用";
            break;
          case "2":
            msg = "禁止";
            break;
          default:
            break;
        }
        return msg;
      },
      /**
       * 根据角色id获取用户列表
       * */
      getUserListByRoleId(params) {
        if (params.sysRoleId == null) {
          return;
        }
        api.getUserListByRoleId(params).then((res) => {
          this.userDataList = res.data.list;
          this.userListPageTotal = parseInt(res.data.total);//页总数
          this.userListPageNo = parseInt(res.data.pageNum);//当前页
        });
      },
      /**
       * 根据用户列表的数据转换
       * */
      formatIsLocked(row) {
        return this.getLockedEnumMsg(row.isLocked);
      },
      /**
       * 根据部门数据转换成部门名称
       * */
      formatSysDeptName(row) {
        return row.sysDept.sysDeptName;
      },
      /**
       * 根据枚举值获取锁定状态的枚举信息
       * */
      getLockedEnumMsg(value) {
        var msg = "";
        switch (value) {
          case 1:
            msg = "可用";
            break;
          case 2:
            msg = "锁定";
            break;
          default:
            break;
        }
        return msg;
      },
      /**
       * 分页组件-改变当前页事件监听
       * */
      currentChangeUserListPage(val) {
        this.getUserListByRoleId({
          sysRoleId: this.roleForm.sysRoleId,
          pageNo: val,
          pageSize: this.userListPageSize
        });
      },
      /**
       * 获取权限树
       * */
      getPrivilegeTree() {
        api.getPrivilegeTree({}).then((res) => {
          this.rightTreeList = res.data;
        });
      },
      /**
       * 打开分配权限窗口
       * */
      openSaveRightRoleDialog() {
        if (this.roleForm.sysRoleId == null) {
          common.message("请选择需要分配权限的角色", "warning");
          return;
        }
        this.rightInfoDialog = true;//先打开弹窗再渲染树，再绑定选择事件
        //根据角色id获取权限数据
        api.getPrivilegeByRoleId({
          roleId: this.roleForm.sysRoleId
        }).then((res) => {
          this.selectRightTreeList = this.getSystemRightIds(res.data);
          this.$nextTick(function () {
            this.$refs.rightTree.setCheckedKeys(this.selectRightTreeList);
          });
        });
      },
      /**
       * 根据权限数据转换成权限id数组
       * */
      getSystemRightIds(param) {
        var resultArray = [];
        if (param instanceof Array) {
          //如果入参是列表
          for (var i = 0; i < param.length; i++) {
            resultArray.push(param[i].sysRightId);
            //子权限为空则跳过子权限循环
            if (param[i].childrenList == null || param[i].childrenList.length <= 0) {
              continue;
            }
            resultArray.concat(this.getSystemRightIds(param[i].childrenList));
          }
          return resultArray;
        }
        //如果入参是对象
        resultArray.push(param.sysRightId);
        //子权限为空直接返回父级权限id
        if (param.childrenList == null || param.childrenList.length <= 0) {
          return resultArray;
        }
        //子权限与父权限id合并
        return resultArray.concat(this.getSystemRightIds(param.childrenList));
      },
      /**
       * 分配权限
       * */
      savePrivilegeRole() {
        this.rightInfoDialog = false;
        api.savePrivilegeRole({
          roleId: this.roleForm.sysRoleId,
          privilegeStr: this.$refs.rightTree.getCheckedKeys().toString()
        }).then((res) => {
          common.generalMessage(res);
          if (res.code == 200) {
            this.getTreeListByRoleId();
          }
        });
      },
      /**
       * 打开新增关联窗口
       */
      addUser() {
        if (this.roleForm.sysRoleId == null) {
          common.message("请选择需要新增关联的角色", "warning");
          return;
        }
        this.addUserInfo = true
        api.getUserList({
          pageNo: 1,
          pageSize: this.userListPageSize
//            sysUserAccount:string,
//            sysUserName:string
        }).then((res) => {
          this.UserList = res.data.list
        })

      },
      handleCurrentChange(val) {
        this.currentRow = val.sysUserId;
      },
      /**
       *新增关联
       */
      saveUser() {
        if (this.currentRow == null) {
          common.message("请选择用户", "warning");
          return;
        }
        this.addUserInfo = false;
        api.saveUserRole({
          roleId: this.roleForm.sysRoleId,
          userId: this.currentRow
        }).then((res) => {
          if (res.code == 403) {
            common.message("操作失败：当前用户未授权", "warning");
            return;
          }
          this.getUserListByRoleId({
            sysRoleId: this.roleForm.sysRoleId,
            pageNo: 1,
            pageSize: this.userListPageSize
          });

        })
      },

    }
  }
</script>

<style lang="scss">
  #roleList {
    .el-pager li.active{
      color:white;
      background-color: #2ba3ff;
    }
    .el-col {
      border-radius: 4px;
    }

    .el-main {
      padding: 0;
    }

    .el-button.is-round {
      border-radius: 6px;
    }

    .el-table__expanded-cell[class*=cell] {
      padding: 20px 0 20px 48px;
    }

    .grid-content {
      margin: 30px;
      border-radius: 4px;
      background: white;
      padding-bottom: 20px;

      h4 {
        border-bottom: 2px solid #F1F1F1;
        margin: 0 20px;
        padding: 10px 0;
      }

      .userHandle {
        padding: 15px 20px;
        line-height: 40px;
        .el-button--primary{
          border-radius:3px;
          background-color: #086dfb;
        }
        .el-button--success{
          border-radius:3px;
          background-color: #2bc792;
        }
        .el-button--danger{
          border-radius:3px;
          background-color: #fc8282;
        }
      }
    }

    .gridLeft {
      margin-right: 2px;
    }

    .gridRight {
      margin-left: 2px;

      .el-pagination {
        margin-top: 20px;
      }
    }

    .row-bg {
      padding: 10px 0;
      background-color: #f9fafc;
    }
  }


</style>



